
/*************************************************************************
 * All portions of code are copyright by their respective author/s.
 * Copyright (C) 2007      Bryan Christ <bryan.christ@hp.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *----------------------------------------------------------------------*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "psthread.h"
#include "pseudo.h"

ps_runq_t *psthread_init(int8_t scheduler)
{
	ps_runq_t		*run_q;

	run_q = (ps_runq_t*)calloc(1,sizeof(ps_runq_t));

	return run_q;
}

ps_task_t*
psthread_add(ps_runq_t *run_q,PSTHREAD callback,void *anything)
{
	ps_task_t	*task;

	if(run_q == NULL || callback == NULL) return NULL;

	task = ps_task_create(callback,anything);

    if(run_q->list == NULL)
    {
        run_q->list = task;
        run_q->task_count++;
        return task;
    }

	ps_task_append(run_q->list,task);
	run_q->task_count++;

	return task;
}

int8_t
psthread_del(ps_runq_t *run_q,ps_task_t *task)
{
	uint16_t task_count;

	if(run_q == NULL || task == NULL) return -1;

	task_count = run_q->task_count;

	if(task_count == 0) return -1;

	run_q->list = ps_task_unlink(task);
	ps_task_destroy(task);

	return 0;
}

void
psthread_run(ps_runq_t *run_q,uint16_t tasks)
{
    ps_task_t   *task;

    if(run_q->task_count == 0) return;

    task = run_q->list;

    task->callback(task,task->anything);

    if(run_q->task_count == 1) return;

    // move the task to the end of the queue
    run_q->list = ps_task_unlink(task);
    ps_task_append(run_q->list,task);

    return;
}

uint16_t
psthread_count(ps_runq_t *run_q)
{
    if(run_q == NULL) return 0;

    return run_q->task_count;
}
